<template>
    <div style=" position: relative;"><el-card>
            <template #header>
                <!-- 搜索 -->
                <div>
                    <el-input clearable v-model="find_data.title" style="width: 240px" placeholder="标题" />
                    <el-button style="margin-left: 20px;height:30px" @click="search_btn" type="primary"
                        icon="Search">搜索</el-button>
                </div>
                <!-- 功能按钮 -->
                <div class="del_btn_Css">
                    <el-button v-if='role_off' @click="add_btn" type="primary" icon="CirclePlusFilled">新增</el-button>
                    <!-- <el-button @click="del_btn" type="danger" icon="DeleteFilled">删除</el-button>
                    <el-button @click="out_btn" type="warning" icon="Promotion">导出</el-button> -->
                </div>
            </template>
            <div>
                <el-table class="list_data_Css" border @selection-change="selection_change_btn" height="63vh"
                    ref="multipleTableRef" :data="list_data">
                    <el-table-column type="selection" width="35" />
                    <el-table-column label="编号" width="55" fixed type="index" />
                    <template v-for="item in table_data_list" :key="item.name">
                        <el-table-column v-if="item.enablePinning" :width="item.minWidth" :prop="item.name"
                            :label="item.displayName">
                            <template v-if="item.name == 'set'" #="{ row, column, $index }">
                                <el-button v-if='role_off' @click="up_btn(row)" type="warning"
                                    icon="QuestionFilled">编辑</el-button>
                                <el-button v-if='role_off' @click="del_btn(row)" type="danger"
                                    icon="RemoveFilled">删除</el-button>
                                <el-button v-if='!role_off' @click="up_btn(row)" type="primary"
                                    icon="RemoveFilled">查看</el-button>
                            </template>
                        </el-table-column>
                    </template>
                </el-table>

            </div>
            <div class="current_change_btn_css">
                <el-pagination @current-change="current_change_btn" @size-change="size_change_btn"
                    v-model:current-page="find_data.pageNo" v-model:page-size="find_data.pageSize"
                    :page-sizes="[20, 50, 100, 200, 500]" :background="true"
                    layout="prev, pager, next, jumper,->,sizes,total," :total="total" />
            </div>
        </el-card>
    </div>

    <!-- 弹窗 -->
    <div>
        <!-- 新增 -->
        <el-dialog style="margin-top:5vh" v-model="add_off" :title="title" width="50%" :close-on-click-modal='false'>
            <el-form label-width="120px">
                <el-form-item label="标题：" required>
                    <el-input v-model="add_data.title" maxlength="20" placeholder="请输入标题(最大长度为20位)" show-word-limit
                        type="text" />
                </el-form-item>
                <el-form-item label="上传附件：">
                    <el-upload :on-success="handleAvatarSuccess" class="up_css"
                        :headers="{ Authorization: GET_TOKEN() }" :action="action" :auto-upload="false" :data="add_data"
                        :on-change="beforeAvatarUpload" ref="uploadRef" :show-file-list="false">
                        <div><span style="margin-left: 10px;">{{ add_data.fileName }}</span>
                        </div>
                    </el-upload>
                    <el-button v-if="up_data.fileName" @click="downloadSuggest_btn" type="primary">下载文件</el-button>


                </el-form-item>
                <el-form-item label="建议内容：" required>
                    <div style="border: 1px solid #ccc">
                        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" />
                        <Editor style="height: 300px; overflow-y: hidden;" v-model="add_data.style"
                            @onCreated="handleCreated" />
                    </div>
                </el-form-item>

            </el-form>
            <div style="display:flex;margin-left:40vw">
                <el-button type="warning" @click="add_no()">返 回</el-button>
                <el-button v-if='role_off' type="primary" @click="add_ok()">确 定</el-button>

            </div>
        </el-dialog>

    </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch, nextTick, shallowRef } from 'vue'
import {
    getExpertSuggestListByPage, saveExpertSuggest, deleteExpertSuggest, downloadSuggest, updateExpertSuggest
} from '@/api/expert_countermeasures.js'
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus'
import '@wangeditor/editor/dist/css/style.css' // 引入富文本编辑器的 CSS 文件
import { Toolbar, Editor } from '@wangeditor/editor-for-vue';
import { ImageUrl_upload } from '@/utils/common.js'
import { GET_TOKEN } from '@/utils/token.js'
import CircularJSON from 'circular-json'
onMounted(async () => {
    let expert_advice = JSON.parse(localStorage.getItem('expert_advice'))
    if (expert_advice) {
        find_data.title = expert_advice.title

        await list_api()
        await role_api()
    } else {
        await list_api()
        await role_api()
    }


})

//#region 登录角色判断 
//   
let role_off = ref(true)
let role_id = ref('')
let role_customerId = ref('')
const role_api = () => {
    let luser = JSON.parse(localStorage.getItem('luser'))
    if (luser.loginName != 'admin') {
        role_off.value = false
        role_id.value = luser.id
        role_customerId.value = luser.customerId
        // checkPointIds.value = []
        // checkPointIds.value.push(role_customerId.value)
        // getCustomerList_list.value = []
        // getCustomerList_list.value.push(role_customerId.value)
    }
}
// #endregion


//#region 分页列表
const list_data = ref([])
const find_data = reactive({
    pageNo: 1,
    pageSize: 20,
    title: '',

})
const total = ref(0)

// 分页器一夜显示多少数据页面
const size_change_btn = () => {
    find_data.pageNo = 1
    list_api()
}

// 分页器跳转页面
const current_change_btn = () => {
    list_api()
}

const list_api = () => {
    const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })
    getExpertSuggestListByPage(find_data).then(res => {

        if (res.resultStatus.resultCode == '0000') {
            list_data.value = res.value.list
            total.value = res.value.total
        } else {
            return ElMessage({
                message: res.resultStatus.resultMessage,
                type: 'warning',
            })
        }
        loading.close()

    })
}
//#endregion

//#region 表格数据处理
const table_data_list = reactive([
    { name: 'title', displayName: '标题', minWidth: '', enablePinning: true },
    { name: 'createTime', displayName: '发布时间', minWidth: '', enablePinning: true },
    { name: 'updateTime', displayName: '修改时间', minWidth: '', enablePinning: true },
    { name: 'set', displayName: '操作', minWidth: '200', enablePinning: true },
])




//#endregion

//#region 表格选择
const table_list = ref([])
const selection_change_btn = (e) => {
    table_list.value = e
    console.log(e)
}
//#endregion

//#region 新增
const action = ref('http://120.78.240.202:8088/exSu/saveExpertSuggest')
const add_off = ref(false)
const add_data = reactive({
    title: '',
    fileName: '点击上传文件',

    context: '',
    style: '',
})
const add_btn = () => {
    add_data.title = ''
    add_data.fileName = '点击上传文件'
    title.value = '新增专家建议:'
    add_data.context = ''
    add_data.style = ''
    up_data.value.fileName = ''
    action.value = 'http://120.78.240.202:8088/exSu/saveExpertSuggest'
    up_off.value = false
    add_off.value = true

}
const uploadRef = ref('')
const rawFile_list = ref([])
const beforeAvatarUpload = (rawFile) => {
    console.log(rawFile)
    add_data.fileName = rawFile.name
    rawFile_list.value = []
    rawFile_list.value.push(rawFile)
    return true

}
const handleAvatarSuccess = (response, uploadFile) => {
    list_api()
    add_off.value = false
}
const add_ok = () => {
    if (!add_data.title) {
        return ElMessage({
            message: '请填写标题',
            type: 'warning',
        })
    } else if (!add_data.style) {
        return ElMessage({
            message: '请填写内容',
            type: 'warning',
        })
    }
    if (add_data.fileName == '点击上传文件') {
        add_data.fileName = ''
    }
    add_data.context = add_data.style.replace(/<[^>]+>/g, '')


    if (up_off.value) {
        if (rawFile_list.value.length > 0) {
            uploadRef.value.submit()

        } else {
            updateExpertSuggest(add_data).then(res => {
                if (res.resultStatus.resultCode == '0000') {
                    list_api()
                    add_off.value = false
                } else {
                    return ElMessage({
                        message: res.resultStatus.resultMessage,
                        type: 'warning',
                    })
                }
            })
        }
    } else {
        if (rawFile_list.value.length > 0) {
            uploadRef.value.submit()

        } else {
            saveExpertSuggest(add_data).then(res => {
                if (res.resultStatus.resultCode == '0000') {
                    list_api()
                    add_off.value = false
                } else {
                    return ElMessage({
                        message: res.resultStatus.resultMessage,
                        type: 'warning',
                    })
                }
            })
        }
    }



}

const add_no = () => {
    add_off.value = false
}
// 富文本
const editorRef = shallowRef()
const handleCreated = (editor) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}

//#endregion
const title = ref('新增专家建议:')
const up_off = ref(false)
const up_data = ref({})
//#region 修改
const up_btn = (e) => {
    add_data.title = e.title
    add_data.fileName = e.fileName ? e.fileName : '点击上传文件'
    add_data.context = e.context
    add_data.style = e.style
    add_data.id = e.id
    up_data.value = e
    title.value = '修改专家建议:'
    action.value = 'http://120.78.240.202:8088/exSu/updateExpertSuggest'
    up_off.value = true
    add_off.value = true

}
const downloadSuggest_btn = () => {
    downloadSuggest({
        filePath: up_data.value.filePath
    }).then(res => {
        let blob = new Blob([res.data], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
        let objectUrl = URL.createObjectURL(blob);
        let a = document.createElement('a');
        document.body.appendChild(a);
        a.setAttribute('style', 'display:none');
        a.setAttribute('href', objectUrl);
        // let fileName= "告警统计列表.xlsx";
        a.setAttribute('download', up_data.value.fileName);
        a.click();
        URL.revokeObjectURL(objectUrl);
    })
}
//#endregion


//#region 删除
const del_btn = (e) => {

    console.log(e)
    ElMessageBox.confirm(
        '是否确认删除该建议?',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
            distinguishCancelAndClose: 'true',
        }
    )
        .then(() => {
            let ps = [e.id]
            deleteExpertSuggest(ps).then(res => {
                if (res.resultStatus.resultCode == '0000') {
                    list_api()
                    return ElMessage({
                        message: res.resultStatus.resultMessage,
                        type: 'success',
                    })
                } else {
                    return ElMessage({
                        message: res.resultStatus.resultMessage,
                        type: 'warning',
                    })
                }
            })
        })
        .catch((e) => {


        })

}
//#endregion

//#region 搜索
const search_btn = () => {
    // localStorage.setItem('expert_advice', CircularJSON.stringify(find_data))
    list_api()

}
//#endregion

</script>

<style scoped lang='scss'>
.up_css {
    cursor: pointer !important;
    width: 100%;
    background: #271e1e2b;
    border-radius: 5px;
}

.del_btn_Css {
    margin-top: 10px;
}

.list_data_Css {
    width: 100%
}

.current_change_btn_css {
    margin-top: 20px
}




.map_input {
    width: 100%;
    position: relative;
    z-index: 1;
    display: flex;
    justify-content: center;

}

.div_bg:hover {
    background-color: darkgray;
}
</style>
<style>
.col-items::-webkit-scrollbar {
    width: 5px !important;
}

.col-items>label {
    margin-left: 0px !important;
    margin-top: 5px;
    width: 100%;
}
</style>
